package com.eastcom.groovy.task.taskdirector.file.xml

import java.awt.TexturePaintContext.Int;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.InetAddress.Cache;
import java.sql.Date;
import java.sql.PreparedStatement
import java.sql.SQLException
import java.sql.Timestamp
import java.sql.Types;
import java.text.SimpleDateFormat
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlValue;

import com.eastcom.groovy.tools.common.JmsJndiConfig
import com.eastcom.groovy.tools.common.MQCommunication
import com.eastcom.groovy.tools.common.ShellExecutor;
import com.eastcom.groovy.tools.db.DbEngine
import com.eastcom.groovy.tools.file.FileUtils;
import com.eastcom.groovy.tools.file.FtpUtils;
import com.eastcom.groovy.tools.file.JaxbUtil;
import com.eastcom.groovy.provider.*
import com.eastcom.groovy.tools.mail.*
import com.sun.java.util.jar.pack.Instruction.Switch;
import com.sun.org.apache.bcel.internal.generic.NEW;
import com.sun.org.apache.bcel.internal.util.ClassPath.Dir;

import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ftp.FTPFile
import org.apache.commons.net.ftp.FTPFileFilter
import org.apache.tools.ant.types.FileList;
import org.springframework.dao.DataAccessException
import org.springframework.jdbc.core.support.AbstractLobCreatingPreparedStatementCallback
import org.springframework.jdbc.support.lob.LobCreator
import org.springframework.jdbc.support.lob.OracleLobHandler
import org.springframework.jdbc.support.nativejdbc.CommonsDbcpNativeJdbcExtractor
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
/**
 * 任务类，可配置
 * @author yuanyue
 *
 */
//CMCC-ADSL|QQ大乐斗|0|0|1|1|2|2|3|3|4|4|5|5|6|6|7|7|8|8|9|9|10|10|11|11|12|12|13|13|14|14|15|15|16|16|17|17|18|18|19|19|20|20|21|21|22|22|23|23
//CMCC-ADSL|QQ飞车|0|0|1|1|2|2|3|3|4|4|5|5|6|6|7|7|8|8|9|9|10|10|11|11|12|12|13|13|14|14|15|15|16|16|17|17|18|18|19|19|20|20|21|21|22|22|23|23
//CMCC-ADSL|反恐精英|0|0|1|1|2|2|3|3|4|4|5|5|6|6|7|7|8|8|9|9|10|10|11|11|12|12|13|13|14|14|15|15|16|16|17|17|18|18|19|19|20|20|21|21|22|22|23|23
//CMCC-ADSL|地下城与勇士|0|0|1|1|2|2|3|3|4|4|5|5|6|6|7|7|8|8|9|9|10|10|11|11|12|12|13|13|14|14|15|15|16|16|17|17|18|18|19|19|20|20|21|21|22|22|23|23
//CMCC-ADSL|大话水浒|0|0|1|1|2|2|3|3|4|4|5|5|6|6|7|7|8|8|9|9|10|10|11|11|12|12|13|13|14|14|15|15|16|16|17|17|18|18|19|19|20|20|21|21|22|22|23|23
//CMCC-ADSL|幻想三国|0|0|1|1|2|2|3|3|4|4|5|5|6|6|7|7|8|8|9|9|10|10|11|11|12|12|13|13|14|14|15|15|16|16|17|17|18|18|19|19|20|20|21|21|22|22|23|23
//CMCC-ADSL|战地之王|0|0|1|1|2|2|3|3|4|4|5|5|6|6|7|7|8|8|9|9|10|10|11|11|12|12|13|13|14|14|15|15|16|16|17|17|18|18|19|19|20|20|21|21|22|22|23|23
//CMCC-ADSL|手机QQ游戏|0|0|1|1|2|2|3|3|4|4|5|5|6|6|7|7|8|8|9|9|10|10|11|11|12|12|13|13|14|14|15|15|16|16|17|17|18|18|19|19|20|20|21|21|22|22|23|23
//CMCC-ADSL|英雄联盟|0|0|1|1|2|2|3|3|4|4|5|5|6|6|7|7|8|8|9|9|10|10|11|11|12|12|13|13|14|14|15|15|16|16|17|17|18|18|19|19|20|20|21|21|22|22|23|23
//CMCC-ADSL|穿越火线|0|0|1|1|2|2|3|3|4|4|5|5|6|6|7|7|8|8|9|9|10|10|11|11|12|12|13|13|14|14|15|15|16|16|17|17|18|18|19|19|20|20|21|21|22|22|23|23
class SimpleXmlFileTaskDirector {
	/**
	 * 对于有特殊要求的txt文件解析
	 */
	/************************配置属性，可以修改，请尽量使用英文防止中文编码问题***************************/
	final String ftpLocalPath = "/export/home/zjcache"
	final String ftpFileNameRegex ="TOP10Game(\\d+).txt"
	//没有时间的话用[]
	final String fileNameTimeFormat ="yyyyMMdd"
	final String timeFormat = "yyyyMMddHH"
	final long fileLimit = 7200000
	final String dstdbBean = "oracle_132_ipnet"
	final int parseLineNumOnce = 1
	final String delimiter = "\\s*\\|\\s*"
	final String encode = "UTF-8"
	final String insertSql = "insert into FLOW_GAME_TOP10_HOUR(TIMESTAMP,NETWORKTYPE,GAMENAME,FLOWAVG,FLOWPEAK) values(?,?,?,?,?)"
	/***************************可配置部分结束***********************************************/

















	static ThreadPoolTaskExecutor threadPoolTaskExecutor
	static List<String> dstFieldList = new ArrayList()
	static List<Integer> dstFieldTypeList = new ArrayList()
	static int[] sqlTypes
	List<List<String>> parseResultList = new ArrayList()
	static Log logger = LogFactory.getLog(SimpleXmlFileTaskDirector.class)



	/*********************initJob和doJob是要被程序调用的方法**************************/
	public boolean initJob(String jobId){
//		doDbInit()
	}

	public boolean doJob(String jobId){
//		doParseFile()
		Zlope_Dns_State zlopeDnsState = JaxbUtil.converyFileToJavaBean("E:\\我的工程文档\\浙江北龙中网DNS日志\\北龙中网上报东信的4个文件\\zlope_statistics.log.important_10.212.212.50_20140916152000_2.xml", "UTF-8", Zlope_Dns_State.class)
		println zlopeDnsState.clazz.get(0).attributes.attrList.get(0).columnCN
		println zlopeDnsState.clazz.get(0).attributes.attrList.get(0).columnEN
		println zlopeDnsState.clazz.get(0).attributes.attrList.get(0).value
//		@XmlAttribute(name ="columnCN")
//		java.lang.String columnCN
//		@XmlAttribute(name ="columnEN")
//		java.lang.String columnEN
//		@XmlValue
//		String value
	}

	private doDbInit(){
		try{
			String reg = "\\w+\\s+\\w+([^\\(\\),]+)\\s*\\(([^\\)]+)"
			String dstTb
			String dstFields
			Pattern pattern = Pattern.compile(reg)
			Matcher matcher = pattern.matcher(insertSql)
			if(matcher.find()){
				dstTb = matcher.group(1)
				dstFields = matcher.group(2)
			}
			DbEngine.loadDb(dstdbBean, dstTb, dstFields, dstFieldList, dstFieldTypeList, true)
			sqlTypes = new int[dstFieldTypeList.size()]
			for(int i = 0; i < dstFieldTypeList.size(); i++){
				sqlTypes[i] = dstFieldTypeList.get(i)
			}
		}catch(Exception e){
			e.printStackTrace()
			logger.error(e.getMessage())
		}
	}
	private boolean doParseFile(){
		try{
			Calendar fileTime = Calendar.getInstance();
			Calendar fileLimitTime = Calendar.getInstance();
			fileLimitTime.setTimeInMillis(new java.util.Date().getTime() - fileLimit);
			File dirs = new File(ftpLocalPath)
			File[] dirFile = dirs.listFiles(new FilenameFilter() {

						@Override
						public boolean accept(File dir, String name) {
							// TODO 自动生成的方法存根
							if(name.matches(ftpFileNameRegex)){
								return true;
							}
							return false;
						}
					});
			for(File f: dirFile){
				long time = f.lastModified();
				fileTime.setTimeInMillis(time);
				if(fileTime.before(fileLimitTime)){
					continue;
				}
				String fileNameTime = null;

				Pattern pat = Pattern.compile(ftpFileNameRegex)
				Matcher mat = pat.matcher(f.getName())
				boolean rs = mat.find()
				if(rs){
					fileNameTime = mat.group(1)
				}else{
					continue
				}
				BufferedReader reader = null;

				try {
					reader = new BufferedReader(new InputStreamReader(new FileInputStream(f), encode));
				} catch (Exception e) {
					e.printStackTrace()
				}
				StringBuilder context = new StringBuilder();
				String line = null;
				boolean isFileEnd = false;
				int counts = 0
				while(!isFileEnd){
					if(parseResultList.size() >= 15000){
						doInsertResult()
					}
					for(int i = 0; i < parseLineNumOnce; i++){
						try {
							line = reader.readLine()
							logger.debug("line="+line)
							if(line == null){
								isFileEnd = true
								break
							}
						} catch (Exception e) {
							e.printStackTrace()
						}
						context.append(line)
					}
					String parseContext = context.toString()

					List<String> valueList = contextParse(fileNameTime,parseContext)
					if(!(valueList == null)){
						parseResultList.addAll(valueList)
					}
					context = new StringBuilder();
					if(isFileEnd){
						logger.debug("文件已经读完！");
						doInsertResult()
						break;
					}
				}
			}
		}catch(Exception e){
			e.printStackTrace()
			logger.error(e.getMessage())
		}
	}

	private List<List<String>> contextParse(String param,String context){
		List<List<String>> valueList =  new ArrayList();
		String[] record = context.split(delimiter)
		println context
		println record.length
		if(record.length != 50){
			return null
		}

		int index = 0
		for(int i = 2; i < 50; ){
			List<String> temp = new ArrayList<String>();
			String time = param
			int hour = i/2 - 1
			if(hour < 10){
				time += ("0"+hour)
			}else{
				time += hour
			}
			String netWorkType = record[0]
			String gameName = record[1]
			String flowAvg = record[i]
			String flowPeak = record[i+1]
			temp.add(time)
			temp.add(netWorkType)
			temp.add(gameName)
			temp.add(flowAvg)
			temp.add(flowPeak)
			valueList.add(temp)
			i+=2
		}
		return valueList
	}

	private boolean doInsertResult(){
		try{
			DbEngine dbEngine = SpringContextProvider.getBean("dbEngine")
			dbEngine.getJdbcUtil().setDataSource(DynamicBeanDomianProvider.getBean(dstdbBean))
			for(List<String> raw: parseResultList){
				Object[] param = new Object[raw.size()]
				println raw.size()
				for(int i = 0; i < raw.size(); i++){
					print raw.get(i)+"--"+sqlTypes[i]+"\t"
					try {
						switch(sqlTypes[i]){
							case Types.INTEGER:
								param[i] = Integer.valueOf(raw.get(i))
								break
							case Types.FLOAT:
							case Types.DOUBLE:
								param[i] = Double.valueOf(raw.get(i))
								break
							case Types.DECIMAL:
							case Types.NUMERIC:
								param[i] = BigDecimal.valueOf(Double.valueOf(raw.get(i)))
								break
							case Types.TIMESTAMP:
								java.util.Date date = new SimpleDateFormat(timeFormat).parse(raw.get(i))
								logger.debug(date)
								param[i] = new Timestamp(date.getTime())
								break
							case Types.DATE:
								java.util.Date date = new SimpleDateFormat(timeFormat).parse(raw.get(i))
								logger.debug(date)
								param[i] = new Date(date.getTime())
								break
							case Types.VARCHAR:
							case Types.NVARCHAR:
								param[i] = raw.get(i)
								break
							case Types.OTHER:
								param[i] = raw.get(i)
								break;
							default:
								param[i] = null
								logger.warn("入库数据库字段无法识别！使用Null插入！")
								break;
						}
					} catch (Exception e) {
						e.printStackTrace()
						logger.error(e.getMessage())
						param[i]=null
					}
				}
				try{
					dbEngine.getJdbcUtil().update(insertSql, param, sqlTypes)
				}catch(Exception e){
					e.printStackTrace()
					logger.error(e.getMessage())
				}
				println ""
			}
			parseResultList.clear()
		}catch(Exception e){
			e.printStackTrace()
			logger.error(e.getMessage())
		}
	}

}
@XmlRootElement(name="resource-data")
@XmlAccessorType(XmlAccessType.FIELD)
class Zlope_Dns_State{
	@XmlElement(name= "class")
	List<Clazz> clazz


	@Override
	public String toString() {
		if(clazz != null){
			StringBuilder builder = new StringBuilder()
			clazz.each {
				builder.append(it.toString()+"\n")
			}
			return builder.toString()
		}
	}	
}
@XmlAccessorType(XmlAccessType.FIELD)
class Clazz{
	@XmlAttribute(name ="zhCN")
	java.lang.String zhCN
	@XmlAttribute(name ="zhEN")
	java.lang.String zhEN
	@XmlElement(name = "attributes")
	Attributes attributes

	@Override
	public String toString() {
		return "Clazz [zhCN=" + zhCN + ", zhEN=" + zhEN + ", attributes="
				+ attributes.toString() + "]\n";
	}	
}

@XmlAccessorType(XmlAccessType.FIELD)
class Attributes{
	@XmlElement(name= "attribute")
	List<Attribute> attrList


	@Override
	public String toString() {
		if(attrList != null){
			StringBuilder builder = new StringBuilder()
			attrList.each {
				builder.append(it.toString()+"\n")
			}
			return builder.toString()
		}
	}	
}

@XmlAccessorType(XmlAccessType.FIELD)
class Attribute{
	@XmlAttribute(name ="columnCN")
	java.lang.String columnCN
	@XmlAttribute(name ="columnEN")
	java.lang.String columnEN
	@XmlValue
	String value

	@Override
	public String toString() {
		return "Attribute [columnCN=" + columnCN + ", columnEN=" + columnEN
				+ ", value=" + value + "]\n";
	}	
}

